<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索区域 -->
      <el-form v-model="queryParams" ref="queryRef" :inline="true" label-width="80px" v-show="showSearch"
        class="search-form">
        <el-form-item label="账户代码" prop="accountCode">
          <el-select v-model="queryParams.accountCode" placeholder="请选择账户代码" style="width: 160px" clearable
            @change="handleQuery">
            <el-option v-for="account in accountList" :key="account.accountCode"
              :label="account.accountCode + ' - ' + account.accountName" :value="account.accountCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="结算单类型" prop="settlementType">
          <el-select v-model="queryParams.settlementType" placeholder="请选择结算单类型" style="width: 120px" clearable
            @change="handleQuery">
            <el-option v-for="item in settlement_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="计算类型" prop="profitCalcType">
          <el-select v-model="queryParams.profitCalcType" placeholder="请选择计算类型" style="width: 120px" clearable
            @change="handleQuery">
            <el-option v-for="item in profit_calc_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="结算状态" prop="settlementStatus">
          <el-select v-model="queryParams.settlementStatus" placeholder="请选择结算状态" style="width: 120px" clearable
            @change="handleQuery">
            <el-option v-for="item in settlement_status" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="beginDate">
          <el-date-picker v-model="queryParams.beginDate" type="date" value-format="YYYY-MM-DD" placeholder="开始日期"
            style="width: 150px" />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="queryParams.endDate" type="date" value-format="YYYY-MM-DD" placeholder="结束日期"
            style="width: 150px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="success" plain icon="Plus" @click="handleAdd" v-hasPermi="['kylin:futureSettlement:add']">
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleBatchDelete"
            v-hasPermi="['kylin:futureSettlement:remove']">
            批量删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Download" @click="openDownloadDialog"
            v-hasPermi="['kylin:futureSettlement:download']">
            下载结算单
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Download" @click="openBatchDownloadDialog"
            v-hasPermi="['kylin:futureSettlement:download']">
            批量下载结算单
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="Upload" :disabled="multiple" @click="handleImportSettlement"
            v-hasPermi="['kylin:futureSettlement:import']">
            导入结算单
          </el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
      </el-row>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="settlementList.data" style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="账户代码" prop="accountCode" width="120" align="center" />
        <el-table-column label="结算日期" prop="settlementDate" width="120" align="center" />
        <el-table-column label="文件名" prop="fileName" align="center" />
        <el-table-column label="结算单类型" prop="settlementType" width="120" align="center">
          <template #default="scope">
            <dict-tag :options="settlement_type" :value="scope.row.settlementType" />
          </template>
        </el-table-column>
        <el-table-column label="利润计算类型" prop="profitCalcType" width="120" align="center">
          <template #default="scope">
            <dict-tag :options="profit_calc_type" :value="scope.row.profitCalcType" />
          </template>
        </el-table-column>
        <el-table-column label="结算状态" prop="settlementStatus" width="120" align="center">
          <template #default="scope">
            <dict-tag :options="settlement_status" :value="scope.row.settlementStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button link type="primary" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['kylin:futureSettlement:edit']">编辑</el-button>
            <el-button link type="primary" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['kylin:futureSettlement:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="settlementList.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>

      <!-- 添加或编辑对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
          <el-form-item label="账户代码" prop="accountCode">
            <el-select v-model="form.accountCode" placeholder="请选择账户代码" style="width: 100%">
              <el-option v-for="account in accountList" :key="account.accountCode"
                :label="account.accountCode + ' - ' + account.accountName" :value="account.accountCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="结算日期" prop="settlementDate">
            <el-date-picker v-model="form.settlementDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择结算日期"
              style="width: 100%" />
          </el-form-item>
          <el-form-item label="文件名" prop="fileName">
            <el-input v-model="form.fileName" placeholder="请输入文件名" style="width: 100%" />
          </el-form-item>
          <el-form-item label="结算单类型" prop="settlementType">
            <el-select v-model="form.settlementType" placeholder="请选择结算单类型" style="width: 100%">
              <el-option v-for="item in settlement_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="利润计算类型" prop="profitCalcType">
            <el-select v-model="form.profitCalcType" placeholder="请选择利润计算类型" style="width: 100%">
              <el-option v-for="item in profit_calc_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="结算状态" prop="settlementStatus">
            <el-select v-model="form.settlementStatus" placeholder="请选择结算状态" style="width: 100%">
              <el-option v-for="item in settlement_status" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 下载对话框 -->
      <el-dialog title="下载期货结算单" v-model="downloadOpen" width="400px" append-to-body>
        <el-form ref="downloadFormRef" :model="downloadForm" :rules="downloadRules" label-width="100px">
          <el-form-item label="账户代码" prop="accountCode">
            <el-select v-model="downloadForm.accountCode" placeholder="请选择账户代码" style="width: 100%">
              <el-option v-for="account in accountList" :key="account.accountCode"
                :label="account.accountCode + ' - ' + account.accountName" :value="account.accountCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="downloadForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="downloadForm.password" type="password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="结算单类型" prop="settlementType">
            <el-select v-model="downloadForm.settlementType" placeholder="请选择结算单类型" style="width: 100%">
              <el-option v-for="item in download_settlement_type" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="结算日期" prop="settlementDate">
            <el-date-picker v-model="downloadForm.settlementDate" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择结算日期" style="width: 100%" :disabled-date="disabledDate" />
          </el-form-item>
          <el-form-item label="利润计算类型" prop="profitCalcType">
            <el-radio-group v-model="downloadForm.profitCalcType">
              <el-radio label="day">逐日盯市</el-radio>
              <el-radio label="trade">逐笔对冲</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="downloadOpen = false">取消</el-button>
            <el-button type="primary" :loading="downloadLoading" @click="handleDownload">下载</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 批量下载对话框 -->
      <el-dialog title="批量下载期货结算单" v-model="batchDownloadOpen" width="500px" append-to-body>
        <el-form ref="batchDownloadFormRef" :model="batchDownloadForm" :rules="batchDownloadRules" label-width="100px">
          <el-form-item label="账户代码" prop="accountCodes">
            <el-checkbox-group v-model="batchDownloadForm.accountCodes">
              <template v-if="accountList && accountList.length > 0">
                <el-checkbox v-for="account in accountList" :key="account.accountCode" :label="account.accountCode"
                  style="display: block; margin: 5px 0;">
                  {{ account.accountCode }} - {{ account.accountName }}
                </el-checkbox>
              </template>
              <template v-else>
                <div style="color: #999; padding: 10px;">正在加载账户列表...</div>
              </template>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="开始日期" prop="beginDate">
            <el-date-picker v-model="batchDownloadForm.beginDate" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择开始日期" style="width: 100%" />
          </el-form-item>
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker v-model="batchDownloadForm.endDate" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择结束日期" style="width: 100%" />
          </el-form-item>
          <el-form-item label="结算单类型" prop="settlementTypes">
            <el-checkbox-group v-model="batchDownloadForm.settlementTypes">
              <el-checkbox v-for="item in download_settlement_type" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="利润计算类型" prop="profitCalcTypes">
            <el-checkbox-group v-model="batchDownloadForm.profitCalcTypes">
              <el-checkbox label="day">逐日盯市</el-checkbox>
              <el-checkbox label="trade">逐笔对冲</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="batchDownloadOpen = false">取消</el-button>
            <el-button type="primary" :loading="batchDownloadLoading" @click="handleBatchDownload">批量下载</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { getAllFutureAccounts } from '@/api/kylin/futureAccount'
import { addFutureSettlement, batchDownloadFutureSettlement, delFutureSettlement, downloadFutureSettlement, getFutureSettlement, getFutureSettlementList, importSettlementToDaily, updateFutureSettlement } from '@/api/kylin/futureSettlement'
import RightToolbar from "@/components/RightToolbar"
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { getCurrentInstance, onMounted, reactive, ref, watch } from 'vue'

// 表格数据
const settlementList = ref({
  data: [],
  total: 0
})

// 加载状态
const loading = ref(false)
// 是否显示搜索条件
const showSearch = ref(true)
// 非多个禁用
const multiple = ref(true)
// 期货账户列表
const accountList = ref([])

// 表单引用
const formRef = ref()
// 弹窗
const open = ref(false)
const downloadOpen = ref(false)
// 下载加载状态
const downloadLoading = ref(false)
// 批量下载弹窗
const batchDownloadOpen = ref(false)
// 批量下载加载状态
const batchDownloadLoading = ref(false)

// 表单数据
const form = reactive({
  id: undefined,
  accountCode: '',
  settlementDate: '',
  fileName: '',

  settlementType: '',
  profitCalcType: '',
  settlementStatus: ''
})

// 下载表单
const downloadForm = reactive({
  username: '',
  password: '',
  settlementType: 'D', // 结算单类型，默认为日报
  settlementDate: '',
  accountCode: '',
  profitCalcType: 'day'
})

// 批量下载表单
const batchDownloadForm = reactive({
  accountCodes: [], // 多选账户代码
  beginDate: '',
  endDate: '',
  settlementTypes: ['D'], // 默认选中日报
  profitCalcTypes: ['day'] // 默认选中逐日盯市
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  accountCode: '', // 修改为''而不是undefined
  beginDate: '',
  endDate: '',
  settlementType: '', // 修改为''而不是undefined
  profitCalcType: '', // 修改为''而不是undefined
  settlementStatus: '' // 修改为''而不是undefined
})

// 选中的行
const ids = ref([])

// 表单标题
const title = ref('')

// 获取当前实例
const { proxy } = getCurrentInstance();

// 初始化字典数据
const { settlement_status } = proxy.useDict('settlement_status');
const { profit_calc_type } = proxy.useDict('profit_calc_type');
const { settlement_type } = proxy.useDict('settlement_type');
// 获取结算单类型字典（用于下载对话框）
const { settlement_type: download_settlement_type } = proxy.useDict('settlement_type');

// 表单校验规则
const rules = {
  accountCode: [
    { required: true, message: '请选择账户代码', trigger: 'change' }
  ],
  settlementDate: [
    { required: true, message: '请选择结算日期', trigger: 'change' }
  ],
  fileName: [
    { required: true, message: '请输入文件名', trigger: 'blur' }
  ],
  settlementType: [
    { required: true, message: '请选择结算单类型', trigger: 'change' }
  ],
  profitCalcType: [
    { required: true, message: '请选择利润计算类型', trigger: 'change' }
  ],
  settlementStatus: [
    { required: true, message: '请选择结算状态', trigger: 'change' }
  ]
}

// 下载表单校验规则
const downloadRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  accountCode: [
    { required: true, message: '请输入账户代码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  settlementType: [
    { required: true, message: '请选择结算单类型', trigger: 'change' }
  ],
  settlementDate: [
    { required: true, message: '请选择结算日期', trigger: 'change' }
  ]
}

// 批量下载表单校验规则
const batchDownloadRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  accountCodes: [
    { required: true, message: '请至少选择一个账户代码', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一个账户代码', trigger: 'change' }
  ],
  beginDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ],
  settlementTypes: [
    { required: true, message: '请至少选择一个结算单类型', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一个结算单类型', trigger: 'change' }
  ],
  profitCalcTypes: [
    { required: true, message: '请至少选择一个利润计算类型', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一个利润计算类型', trigger: 'change' }
  ]
}

// 监听账户代码变化，自动填充结算单账号和密码
watch(() => downloadForm.accountCode, (newAccountCode) => {
  if (newAccountCode) {
    const selectedAccount = accountList.value.find(
      account => account.accountCode === newAccountCode
    )
    if (selectedAccount) {
      // 将结算单账号填入用户名，结算单密码填入密码
      downloadForm.username = selectedAccount.settlementAccount || ''
      downloadForm.password = selectedAccount.settlementPassword || ''
    }
  }
}, { immediate: false })

// 初始化
onMounted(async () => {
  getList()
  // 加载期货账户列表
  await loadAccountList()
})

// 加载期货账户列表
const loadAccountList = async () => {
  try {
    const response = await getAllFutureAccounts()
    // 确保数据格式正确，转换为数组
    const data = response?.data
    accountList.value = Array.isArray(data) ? data : []
    console.log('加载账户列表成功，共', accountList.value.length, '个账户')
  } catch (error) {
    console.error('加载账户列表失败:', error)
    ElMessage.error('获取期货账户列表失败：' + (error.response?.data?.msg || error.message))
    accountList.value = []
  }
}

// 获取数据列表
const getList = async () => {
  loading.value = true
  // 添加调试日志，检查queryParams中的settlementType值
  console.log('查询参数:', JSON.stringify(queryParams))
  console.log('结算单类型:', queryParams.settlementType)
  try {
    const response = await getFutureSettlementList(queryParams)
    // 正确处理后台返回的数据格式，将rows赋值给data
    settlementList.value.data = response?.data?.rows || []
    settlementList.value.total = response?.data?.total || 0
  } catch (error) {
    ElMessage.error('获取数据失败：' + (error.response?.data?.msg || error.message))
    // 确保出错时数据也是空数组，避免表格渲染问题
    settlementList.value.data = []
    settlementList.value.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    accountCode: '',
    beginDate: '',
    endDate: '',
    settlementType: '', // 修改为''而不是undefined，更符合URL参数标准
    profitCalcType: '', // 修改为''而不是undefined
    settlementStatus: '' // 修改为''而不是undefined
  })
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 当前页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 多选
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  // 更新批量操作按钮的禁用状态
  multiple.value = !selection.length
}

// 新增
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '新增期货结算单'
}

// 修改
const handleUpdate = async (row) => {
  try {
    // 获取详情数据
    const response = await getFutureSettlement(row.id)
    const settlementData = response?.data || {};

    // 字段名映射：后端下划线命名 -> 前端驼峰命名
    form.id = settlementData.id;
    form.accountCode = settlementData.account_code || '';  // 后端: account_code
    form.settlementDate = settlementData.settlement_date || '';  // 后端: settlement_date
    form.fileName = settlementData.file_name || '';  // 后端: file_name

    form.settlementType = settlementData.settlement_type || '';  // 后端: settlement_type
    form.profitCalcType = settlementData.profit_calc_type || '';  // 后端: profit_calc_type
    form.settlementStatus = settlementData.settlement_status || '';  // 后端: settlement_status

    // 打开弹窗
    open.value = true;
    title.value = '修改期货结算单';
  } catch (error) {
    ElMessage.error('获取详情失败：' + (error.response?.data?.msg || error.message));
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除结算单 ${row.id} 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await delFutureSettlement({ settlementIds: [row.id] })
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      ElMessage.error('删除失败：' + (error.response?.data?.msg || error.message))
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (ids.value.length === 0) {
    ElMessage.warning('请选择要删除的结算单')
    return
  }
  ElMessageBox.confirm(
    `确定要删除选中的 ${ids.value.length} 条结算单吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await delFutureSettlement({ settlementIds: ids.value })
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      ElMessage.error('删除失败：' + (error.response?.data?.msg || error.message))
    }
  })
}

// 月末日期判断函数已移除

// 根据结算单类型限制可选择的日期
const disabledDate = (time) => {
  // 如果是月报，只允许选择月末日期
  if (downloadForm.settlementType === 'M') {
    const d = new Date(time);
    const lastDay = new Date(d.getFullYear(), d.getMonth() + 1, 0);
    return d.getDate() !== lastDay.getDate();
  }
  return false; // 日报时不限制
};

// 打开下载弹窗
const openDownloadDialog = () => {
  downloadForm.username = ''
  downloadForm.password = ''
  downloadForm.settlementType = 'D' // 默认为日报
  downloadForm.settlementDate = ''
  downloadForm.accountCode = 'hy' // 默认为hy
  downloadForm.profitCalcType = 'day'
  downloadOpen.value = true
}

// 打开批量下载弹窗
const openBatchDownloadDialog = async () => {
  // 确保账户列表已加载
  if (!accountList.value || accountList.value.length === 0) {
    await loadAccountList()
  }

  // 账户默认全部选中
  batchDownloadForm.accountCodes = accountList.value.map(account => account.accountCode)

  // 开始日期和结束日期默认今天
  const today = new Date().toISOString().split('T')[0]
  batchDownloadForm.beginDate = today
  batchDownloadForm.endDate = today

  // 结算单类型默认选中日报
  batchDownloadForm.settlementTypes = ['D']

  // 利润计算类型全选
  batchDownloadForm.profitCalcTypes = ['day', 'trade']

  batchDownloadOpen.value = true
}

// 交易日检查函数已移至后端实现

// 结算单检查函数已移至后端实现

// 批量下载结算单
const handleBatchDownload = async () => {
  // 表单校验
  if (!batchDownloadForm.accountCodes || batchDownloadForm.accountCodes.length === 0) {
    ElMessage.warning('请至少选择一个账户代码')
    return
  }
  if (!batchDownloadForm.beginDate) {
    ElMessage.warning('请选择开始日期')
    return
  }
  if (!batchDownloadForm.endDate) {
    ElMessage.warning('请选择结束日期')
    return
  }
  if (!batchDownloadForm.settlementTypes || batchDownloadForm.settlementTypes.length === 0) {
    ElMessage.warning('请至少选择一个结算单类型')
    return
  }
  if (!batchDownloadForm.profitCalcTypes || batchDownloadForm.profitCalcTypes.length === 0) {
    ElMessage.warning('请至少选择一个利润计算类型')
    return
  }

  // 验证日期范围
  if (new Date(batchDownloadForm.beginDate) > new Date(batchDownloadForm.endDate)) {
    ElMessage.warning('开始日期不能晚于结束日期')
    return
  }

  // 设置加载状态
  batchDownloadLoading.value = true

  try {
    // 显示确认对话框
    ElMessageBox.confirm(
      '即将开始批量下载结算单，该过程可能需要较长时间，请耐心等待。',
      '批量下载确认',
      {
        confirmButtonText: '确认下载',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      try {
        // 调用后端批量下载接口
        const response = await batchDownloadFutureSettlement(batchDownloadForm);

        // 显示成功消息
        ElMessage.success(response.msg || '批量下载成功');

        // 关闭对话框
        batchDownloadOpen.value = false;

        // 刷新列表
        getList();

        // 如果有失败的任务，显示详细失败信息
        if (response.data?.fail_count > 0 && response.data?.fail_messages?.length > 0) {
          ElMessageBox.alert(
            '下载失败详情：<br/>' + response.data.fail_messages.join('<br/>'),
            '批量下载结果',
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '确定'
            }
          );
        }
      } catch (error) {
        ElMessage.error('批量下载失败：' + (error.response?.data?.msg || error.message));
      } finally {
        batchDownloadLoading.value = false;
      }
    }).catch(() => {
      batchDownloadLoading.value = false;
    });
  } catch (error) {
    ElMessage.error('批量下载过程发生错误：' + (error.message || '未知错误'));
    batchDownloadLoading.value = false;
  }
}

// 下载结算单
const handleDownload = async () => {
  // 表单校验
  if (!downloadForm.accountCode) {
    ElMessage.warning('请输入账户代码')
    return
  }
  if (!downloadForm.username) {
    ElMessage.warning('请输入用户名')
    return
  }
  if (!downloadForm.password) {
    ElMessage.warning('请输入密码')
    return
  }
  if (!downloadForm.settlementType) {
    ElMessage.warning('请选择结算单类型')
    return
  }
  if (!downloadForm.settlementDate) {
    ElMessage.warning('请选择结算日期')
    return
  }
  if (!downloadForm.profitCalcType) {
    ElMessage.warning('请选择利润计算类型')
    return
  }

  // 校验：结算单类型为月报时，结算日期必须为月末
  if (downloadForm.settlementType === 'M' && !isLastDayOfMonth(downloadForm.settlementDate)) {
    ElMessage.warning('月报结算单的结算日期必须为月末日期')
    return
  }

  // 设置下载中状态，禁用按钮并显示加载动画
  downloadLoading.value = true
  try {
    const response = await downloadFutureSettlement(downloadForm)

    // 下载成功后，将相关信息保存到期货结算单管理表
    // 将日期格式化为YYYYMMDD
    const dateStr = downloadForm.settlementDate.replace(/-/g, '');
    const settlementData = {
      accountCode: downloadForm.accountCode,
      settlementDate: downloadForm.settlementDate,
      // 生成文件名，格式为：账户代码_结算日期_结算单类型_利润计算类型.xls
      fileName: `${downloadForm.accountCode}_${dateStr}_${downloadForm.settlementType}_${downloadForm.profitCalcType}.xls`,
      // 结算类型：使用表单中选择的结算单类型
      settlementType: downloadForm.settlementType,
      // 利润计算类型直接保存原始值：day 或 trade
      profitCalcType: downloadForm.profitCalcType,
      // 结算状态保存为数字1表示已下载
      settlementStatus: '1'
    }

    // 调用添加接口保存到数据库
    await addFutureSettlement(settlementData)

    ElMessage.success('下载成功并已保存到结算单管理')
    downloadOpen.value = false
    getList() // 刷新列表
  } catch (error) {
    ElMessage.error('下载失败：' + (error.response?.data?.msg || error.message))
  } finally {
    // 无论成功失败，都重置加载状态
    downloadLoading.value = false
  }
}

// 表单重置
const reset = () => {
  form.id = undefined
  form.accountCode = ''
  form.settlementDate = ''
  form.fileName = ''
  form.settlementType = ''
  form.profitCalcType = ''
  form.settlementStatus = ''
  if (formRef && formRef.value) {
    formRef.value.resetFields()
  }
}

// 取消
const cancel = () => {
  reset()
  open.value = false
}

// 提交表单
const submitForm = async () => {
  try {
    if (formRef && formRef.value) {
      await formRef.value.validate()
      let response
      if (form.id) {
        // 修改结算单：通过id修改，确保只传递必要的数据
        response = await updateFutureSettlement(form.id, form)
      } else {
        // 新增结算单
        response = await addFutureSettlement(form)
      }
      ElMessage.success(response.msg || '操作成功')
      open.value = false
      getList()
    }
  } catch (error) {
    if (error.response) {
      ElMessage.error('操作失败：' + (error.response?.data?.msg || error.message))
    } else if (error !== 'cancel') {
      // 验证失败不显示错误信息
    }
  }
}

// 导入结算单到资金日报
const handleImportSettlement = async () => {
  if (ids.value.length === 0) {
    ElMessage.warning('请选择要导入的结算单')
    return
  }

  try {
    // 显示导入开始通知
    ElNotification({
      title: '开始导入',
      message: `正在导入 ${ids.value.length} 个结算单，请勿关闭页面...`,
      type: 'info',
      duration: 5000 // 5秒自动关闭
    })

    // 获取选中的行数据
    const selectedRows = settlementList.value.data.filter(row => ids.value.includes(row.id))
    let successCount = 0
    let failCount = 0
    let failMessages = []

    // 逐行导入
    for (let i = 0; i < selectedRows.length; i++) {
      const row = selectedRows[i]

      try {
        // 发送导入请求
        await importSettlementToDaily({
          id: row.id,
          accountCode: row.accountCode,
          settlementDate: row.settlementDate,
          fileName: row.fileName,
          settlementType: row.settlementType,
          profitCalcType: row.profitCalcType
        })

        successCount++

        // 显示进度通知
        ElNotification({
          title: '导入进度',
          message: `已完成 ${successCount + failCount}/${selectedRows.length} 个结算单导入\n当前成功：${successCount}，失败：${failCount}`,
          type: 'info',
          duration: 5000
        })

      } catch (error) {
        failCount++
        const errorMsg = `${row.accountCode} ${row.settlementDate}：${error.response?.data?.msg || '导入失败'}`
        failMessages.push(errorMsg)

        // 显示失败通知
        ElNotification({
          title: '导入失败',
          message: errorMsg,
          type: 'error',
          duration: 5000
        })
      }
    }

    // 显示最终结果
    ElNotification({
      title: '导入完成',
      message: `总共 ${selectedRows.length} 个结算单\n成功：${successCount} 个\n失败：${failCount} 个`,
      type: successCount === selectedRows.length ? 'success' : 'warning',
      duration: 5000
    })

    // 如果有失败的，显示详细错误信息
    if (failMessages.length > 0) {
      ElMessageBox.alert(
        '导入失败详情：<br/>' + failMessages.join('<br/>'),
        '导入结果',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定'
        }
      )
    }

  } catch (error) {
    ElMessage.error('导入过程发生错误：' + (error.message || '未知错误'))
  } finally {
    // 清除选中状态
    ids.value = []
    multiple.value = true
    // 导入完成后刷新列表，根据当前查询条件重新查询数据
    getList()
  }
}
</script>

<style scoped>
.search-form .el-form-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.search-form .el-form-item__label {
  padding-right: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>